<?php
/**
 * Created by PhpStorm.
 * User: FKL
 * Date: 2016/9/13
 * Time: 11:00
 */

namespace Icsoc\DataBundle\Model;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Icsoc\CoreBundle\Logger\ActionLogger;

/**
 * Class BusinessGroupModel
 * @package Icsoc\DataBundle\Model
 */
class PhoneGroupModel
{
    /** @var \Doctrine\DBAL\Connection  */
    private $conn;
    private $logger;
    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->conn = $this->container->get('doctrine.dbal.default_connection');
        $this->logger = $this->container->get('logger');
    }

    /**
     * @param array $param
     * @return array
     */
    public function listPhoneGroup($param = array())
    {
        $vccId = isset($param['vcc_id']) ? $param['vcc_id'] : '';
        $info = empty($param['info']) ? '' : $param['info'];

        if (empty($vccId)) {
            return array('code'=>402, 'message'=>'企业ID不能为空');
        }
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return array('code' => 403, 'message' => 'info格式非json');
            }
        }

        $where = "";
        if (isset($addInfo['filter'])) {
            $where .= isset($addInfo['filter']['keyword']) && !empty($addInfo['filter']['keyword']) ?
                " AND group_name LIKE '%".$addInfo['filter']['keyword']."%' " : '';
        }

        $count = $this->conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_phone_group '.
            'WHERE vcc_id = :vid '.$where,
            array('vid'=>$vccId)
        );

        $phone = array();
        $page = $this->container->get("icsoc_data.helper")->getPageInfo($count, 'win_phone_group', $addInfo);
        $data = $this->conn->fetchAll(
            "SELECT id,group_name,remark,vcc_id".
            " FROM win_phone_group ".
            'WHERE vcc_id = :vid '.$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            array('vid'=>$vccId)
        );
        foreach ($data as $key => $val) {
            $id = $val['id'];
            $phone[$key] = $this->conn->fetchAll("SELECT c.phone FROM win_phone_group as a LEFT JOIN win_phoid_gid as b ON a.id=b.group_id LEFT JOIN cc_phone400s as c ON b.phone_id = c.phone_id WHERE a.id=$id");
        }
        foreach ($phone as $key => $val) {
            $text = '';
            foreach ($val as $v) {
                if (!empty($v)) {
                    $text .= $v['phone'].',';
                }
            }
            $data[$key]['phone'] = trim($text, ',');
        }

        return array(
            'code' => 200,
            'message' =>'ok',
            'total' => $count,
            'page' => $page['page'],
            'totalPage' => $page['totalPage'],
            'data' => $data,
        );
    }

    /**
     * @param int    $vccId
     * @param string $groupName
     * @return array
     */
    public function addPhoneGroup($vccId = 0, $groupName = '', $phoneId = '', $remark='')
    {
        if (empty($vccId)) {
            return array('code'=>401, 'message'=>'企业ID不能为空');
        }
        if (empty($groupName)) {
            return array('code'=>402, 'message'=>'号码组名称不能为空');
        }
        $rst = $this->checkPhoneGroup($vccId, $groupName, 0);

        if ($rst['code'] != 200) {
            return $rst;
        }
        $param = array('vcc_id'=>$vccId, 'flag'=>1);
        $phoneId = explode(",", $phoneId);
        $param['phones'] = $phoneId;
        try {
            $this->conn->insert('win_phone_group', array('vcc_id'=>$vccId, 'group_name'=>$groupName ,'remark'=>$remark));
            $param['group_id'] = $this->conn->lastInsertId();
            $this->allotAgentBusinessGroup($param);
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code'=>400, 'message'=>'数据库执行错误');
        }

        /** 记录系统操作日志 */
        $content = $this->container->get('translator')
            ->trans(
                "Add Phone Group %groupName%",
                array('%groupName%'=>$groupName)
            );

        $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_ADD, $content);

        return array('code'=>200, 'message'=>'success');
    }

    /**
     * @param int    $id
     * @param string $groupName
     * @param int    $vccId
     * @return array
     */
    public function editPhoneGroup($id = 0, $groupName = '', $vccId = 0, $phoneId = '', $remark='')
    {
        if (empty($id)) {
            return array('code'=>401, 'message'=>'ID不能为空');
        }
        if (empty($groupName)) {
            return array('code'=>402, 'message'=>'号码组名称不能为空');
        }
        $rst = $this->checkPhoneGroup($vccId, $groupName, $id);

        if ($rst['code'] != 200) {
            return $rst;
        }
        $param = array('vcc_id'=>$vccId, 'flag'=>1);
        $phoneId = explode(",", $phoneId);
        $param['phones'] = $phoneId;
        try {
            $name = $this->conn->fetchColumn(
                'SELECT group_name FROM win_phone_group WHERE id = :id',
                array('id'=>$id)
            );
            $this->conn->update('win_phone_group', array('group_name'=>$groupName, 'remark'=>$remark), array('id'=>$id));
            $param['group_id'] = $id;
            $this->allotAgentBusinessGroup($param);
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code'=>400, 'message'=>'数据库执行错误');
        }

        /** 记录系统操作日志 */
        $logStr = sprintf('group_name:%s=>%s', $name, $groupName);
        $content = $this->container->get("translator")->trans(
            "Upload Phone Group %str%",
            array('%str%'=>$logStr)
        );

        $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_UPDATE, $content);

        return array('code'=>200, 'message'=>'success');
    }

    /**
     * @param string $ids
     * @param int    $vccId
     * @return array
     * @throws \Doctrine\DBAL\ConnectionException
     */
    public function deletePhoneGroup($ids = '', $vccId = 0)
    {
        if (empty($ids)) {
            return array('code'=>401, 'message'=>'ID不能为空');
        }
        if (empty($vccId)) {
            return array('code'=>402, 'message'=>'企业ID不能为空');
        }

        $idArr = explode(',', $ids);
        $this->conn->beginTransaction();
        $error = 0;

        try {
            foreach ($idArr as $id) {
                $this->conn->delete('win_phone_group', array('id' => $id));
                $this->conn->delete('win_phoid_gid', array('group_id' => $id));
                //$this->conn->update('win_agent', array('id' => 0), array('id' => $id, 'vcc_id' => $vccId));
            }
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());
            $error++;
        }

        if (!empty($error)) {
            $this->conn->rollBack();

            return array('code'=>400, 'message'=>'数据库执行错误');
        }

        $this->conn->commit();

        /** 记录系统操作日志 */
        $logStr = $this->container->get('translator')->trans(
            'Delete Phone Group %str%',
            array('%str%'=>$ids)
        );
        $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_DELETE, $logStr);

        return array('code'=>200, 'message'=>'删除成功');
    }

    /**
     * 批量分配号码组
     * Array
    (
    [vcc_id] => 1
    [group_id] => 6
    [flag] => 1
    [phones] => Array
    (
    [0] => 1
    [1] => 19
    )

    )
     * @param array $param
     * @return array|string
     */
    public function allotAgentBusinessGroup($param)
    {
        $vccId = empty($param['vcc_id']) ? 0 : $param['vcc_id'];
        $groupId = empty($param['group_id']) ? 0 : $param['group_id'];
        $phones = empty($param['phones']) ? array() : $param['phones'];
        $actionFlag = empty($param['flag']) ? 1 : $param['flag'];
        $data['vcc_id'] = $vccId;
        $data['group_id'] = $groupId;
        if (empty($vccId)) {
            return array('code' => 401, 'message' => '企业ID为空');
        }

        //验证号码组id 是否属于该企业；
        if (!empty($groupId)) {
            try {
                $rst = $this->conn->fetchAssoc("SELECT id FROM win_phone_group WHERE id=$groupId AND vcc_id=$vccId");
            } catch (\Exception $e) {
                $this->logger->error($e->getMessage());

                return array('code'=>400, 'message'=>'数据库操作失败');
            }
            if (empty($rst)) {
                return array('code' => 402, 'message' => '号码组不属于该企业');
            }
        } else {
            return array('code' => 403, 'message' => '号码组ID为空');
        }
        if (empty($phones)) {
            return array('code'=>404, 'message'=>'号码参数为空');
        }
        $username = $this->container->get('security.token_storage')->getToken()->getUsername();
        $ip = $this->container->get('request')->getClientIp();
        try {
            if ($actionFlag == 1) {
                $this->conn->delete('win_phoid_gid', array('group_id'=>$groupId, 'vcc_id'=>$vccId));
                foreach ($phones as $val)
                {
                    $data['phone_id'] = $val;
                    $this->conn->insert('win_phoid_gid', $data);
                }
            } else {
                foreach ($phones as $val)
                {
                    $this->conn->delete('win_phoid_gid', array('phone_id'=>$val, 'vcc_id'=>$vccId));
                }
            }
            $this->logger->info(
                sprintf(
                    "修改号码组ip【%s】vccId【%s】userNmae【%s】phones【%s】groupId【%s】",
                    $ip,
                    $vccId,
                    $username,
                    json_encode($phones),
                    $groupId
                )
            );
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code'=>400, 'message'=>'数据库操作失败');
        }

        return array("code" => 200, 'message' => 'success');
    }


    /**
     * 检测号码组名称是否存在
     * @param int    $vccId
     * @param string $groupName
     * @param int    $id
     * @return array
     */
    public function checkPhoneGroup($vccId = 0, $groupName = '', $id = 0)
    {
        if (empty($vccId)) {
            return array('code'=>401, 'message'=>'企业ID不能为空');
        }
        if (empty($groupName)) {
            return array('code'=>402, 'message'=>'号码组名称不能为空');
        }

        try {
            $result = $this->conn->fetchAll("SELECT * FROM win_phone_group WHERE vcc_id=$vccId AND group_name='$groupName' AND id <> $id");
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code'=>400, 'message'=>'数据库执行错误');
        }
        if (!empty($result)) {
            return array('code'=>403, 'message'=>'号码组名称已存在');
        }

        return array('code'=>200, 'message'=>'success');
    }

    /**
     * 获取号码信息
     * @return array
     */
    public function listPhone(array $param = array())
    {
        $vccId = empty($param['vcc_id']) ? 0 : $param['vcc_id'];
        $id = empty($param['id']) ? 0 : $param['id'];
        $infos = empty($param['info']) ? '' : json_decode($param['info']);
        try{
            //所有的号码
            $allPhones = $this->conn->fetchAll("SELECT phone_id,phone FROM cc_phone400s WHERE vcc_id=$vccId AND phone LIKE "."'%".$infos."%'");
            //所有已经分配的号码
            $usePhones = $this->conn->fetchAll("SELECT phone_id,group_id FROM win_phoid_gid WHERE vcc_id=$vccId");
            //选中的号码组分配好的号码id
            $thisPhones = $this->conn->fetchAll("SELECT phone_id,group_id FROM win_phoid_gid WHERE vcc_id=$vccId AND group_id=$id");
        }catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code'=>400, 'message'=>'数据库执行错误');
        }
        $joinPhone = array();           //根据$thisPhone中的phone_id获取号码，放到$joinPhone中
        foreach ($allPhones as $key=>$val)
        {
            if (!empty($thisPhones)) {
                foreach ($thisPhones as $k=>$v)
                {
                    if ($val['phone_id'] == $v['phone_id'])
                    {
                        $joinPhone[] = $allPhones[$key];
                    }
                }
            }
            foreach ($usePhones as $ky=>$vl)
            {
                if ($val['phone_id'] == $vl['phone_id'])
                {
                    unset($allPhones[$key]);
                }
            }
        }

        return  array('code'=>200, 'data'=> array('all'=>array_values($allPhones), 'old'=>array_values($joinPhone)));
    }

}
